#!/bin/bash
############################################################
# 日期：2020-12-3
# 作者：0719.tech
# 说明：传输springboot.jar到目标linux并调用startsh
############################################################
version="0.1"
echo "$0 version: $version"

usage() {
    echo "Usage: sh deploy4springboot.sh project_dir git_branch build_display_name start_dir command"
    exit 1
}

command="$5"
host_ip="$6"
host_workspace="$7"

if [ -z "$command" ]; then
    command="restart"
fi

if [ -z "$host_ip" ]; then
    host_ip="192.168.138.70"
fi

if [ -z "$host_workspace" ]; then
    host_workspace="/workspace"
fi

if [ "$host_ip" == "" ]; then
    echo -e "\033[0;31m host_ip不能为空 \033[0m"
    exit 1
fi

if [ "$host_workspace" == "" ]; then
    echo -e "\033[0;31m host_workspace不能为空 \033[0m"
    exit 1
fi

echo "command:$command"
echo "host_ip:$host_ip"
echo "host_workspace:$host_workspace"

project_dir="$1"
echo "project_dir:$project_dir"

branch="$2" #"master/dev"
branch=${branch#*/}
echo "git_branch:$branch"

app_name=${project_dir##*/}
echo "app_name:$app_name"

build_name="$3" #"$BUILD_DISPLAY_NAME"
echo "build_name:$build_name"

#启动程序所在目录
start_dir=""
if [ "$4" != "" ];
then
start_dir="/$4"
fi
start_target_dir="$project_dir$start_dir/target"
echo "start_target_dir:$start_target_dir"
ext="${branch}_${build_name}"

for file in `find $start_target_dir -name *.jar`
do
  jar_name=${file##*/}
  new_jar_name=`echo $jar_name|sed 's/.jar/_'$ext'.jar/g'`
done

echo "jar_name:$jar_name"
echo "new_jar_name:$new_jar_name"

#host上的scripts目录
host_script_dir="$host_workspace/scripts"
#应用home
host_app_home="$app_name/$branch"
#应用所在目录
host_jar_dir="$host_workspace/app/$host_app_home"
#host上的jar
host_jar_file="$host_jar_dir/$new_jar_name"

# 传送jar
echo "ssh root@$host_ip \"mkdir -p $host_jar_dir\""
ssh root@$host_ip "mkdir -p $host_jar_dir"
echo "scp $start_target_dir/$jar_name root@$host_ip:$host_jar_file"
scp $start_target_dir/$jar_name root@$host_ip:$host_jar_file

# 传送scripts
project_script_dir="$project_dir/scripts"
echo "scp -r $project_script_dir/start.sh root@$host_ip:$host_jar_dir/start.sh"
scp $project_script_dir/start.sh root@$host_ip:$host_jar_dir/start.sh

#生成启动脚本
echo "ssh root@$host_ip \"cd $host_jar_dir; sed -i 's@{app_home}@$host_app_home@g' start.sh; sed -i 's@{jar_file}@$host_jar_file@g' start.sh; sed -i 's@{script_dir}@$host_script_dir@g' start.sh;\""
ssh root@$host_ip "cd $host_jar_dir; sed -i 's@{jar_file}@$host_jar_file@g' start.sh; sed -i 's@{script_dir}@$host_script_dir@g' start.sh;"

#调用启动脚本,5分钟超时
echo "timeout 300s ssh root@$host_ip \"cd $host_jar_dir; chmod +x *.sh;sh start.sh $command\""
timeout 300s ssh root@$host_ip "cd $host_jar_dir; chmod +x *.sh;sh start.sh $command"

# 检查状态
echo "ssh root@$host_ip \"cd $host_jar_dir; chmod +x *.sh;sh start.sh status\""
ssh root@$host_ip "cd $host_jar_dir; chmod +x *.sh;sh start.sh status"
